/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.msg.hrappy.web.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.msg.hrappy.backend.model.Job;
import edu.msg.hrappy.backend.model.User;
import edu.msg.hrappy.backend.service.DepartmentTypeService;
import edu.msg.hrappy.backend.service.JobService;
import edu.msg.hrappy.backend.service.UserService;

/**
 *
 * @author toroke
 */
public class OnePozitionServlet extends HttpServlet {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB
    private JobService jobService;
    @EJB
    private DepartmentTypeService depService;
    @EJB
    private UserService userService;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.getSession().setAttribute("er", null);
        HttpSession session = req.getSession();
    	User user = userService.getUserByUserName(req.getUserPrincipal()
				.toString());
		session.setAttribute("userId", user.getId());
		session.setAttribute("username", user.getUserName());
        Long id = Long.parseLong(req.getParameter("jobId"));
        
        Job job = jobService.getById(id);
        
      session.setAttribute("job", job);
        String address = "./OnePozition.jsp";

        RequestDispatcher dispatcher = req.getRequestDispatcher(address);

        dispatcher.forward(req, resp);

    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.getSession().setAttribute("er", null);
        HttpSession session = req.getSession();
    	User user = userService.getUserByUserName(req.getUserPrincipal()
				.toString());
		session.setAttribute("userId", user.getId());
		session.setAttribute("username", user.getUserName());
        Long id = Long.parseLong(req.getParameter("jobId"));
        Job job = jobService.getById(id);
        job.setActive(!job.isActive());
        if(job.isActive() == true){
            if (job.getNrOfPositions() == 0){
                job.setNrOfPositions(1);
            }
        }
        jobService.update(job);
        session.setAttribute("job", job);
        String address = "./OnePozition.jsp";

        RequestDispatcher dispatcher = req.getRequestDispatcher(address);

        dispatcher.forward(req, resp);

    }
    
}
